"""用户视图模块"""
import datetime
import re

from django.shortcuts import render
from rest_framework.views import APIView
from sqlalchemy.sql.functions import now

import  common.db_util as db_util
from common import local_cache
from common.http_util  import *
from system.system_models import UserRole, UserLoginLog, User


'''用户登录界面'''
def to_login(request):
    return render(request, "page/system/sys_login.html")

'''用户登录'''
class UserLogin(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        # 查询数据库中的用户信息
        sql =" select * from sys_user where username = :username and password = :password"
        params = {
            "username":username,
            "password":password
        }
        user = db_util.MySqlDb.query_one(sql, params)
        
        # 获取登录IP和浏览器信息
        ip_address = self.get_client_ip(request)
        user_agent = request.META.get('HTTP_USER_AGENT', '')
        login_time = datetime.datetime.now()
        
        #判断是否存在用户
        if user is None:
            # 记录登录失败日志
            self.save_login_log(request,user_name=username,login_tag="登录失败",operate_info="用户名或密码错误",status='failed')
            return Response(Result(code=400,msg='用户名或密码错误'))
        else:
            #将用户信息存入缓存
            local_cache.LocalCache.set("user",user)
            #存入session
            '''已登录成功的标志'''
            request.session["login_flag"] = "have_login"
            '''存入用户信息'''
            request.session["user_info"] = user
            
            # 记录登录成功日志
            self.save_login_log(request,user_name=username,status='success',login_tag="登录成功")
            
            return Response(Result(data={"id":user["id"]}))
    
    def get_client_ip(self, request):
        """获取客户端IP地址"""
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR', '')
        return ip
    
    def save_login_log(self,request,user_name="",login_tag="PC登录",operate_info="--",status='success'):
        try:
            # 创建登录日志对象
            userLoginLog: UserLoginLog = UserLoginLog()
            # 字段：id ,user_name ,login_ip ,login_location ,browser ,os ,login_tag ,operate_info ,status ,login_date ,create_date
            userLoginLog.user_name = user_name
            userLoginLog.login_ip = request.META.get('REMOTE_ADDR')
            userLoginLog.login_location = request.META.get('HTTP_X_FORWARDED_FOR')
            
            # 获取 User-Agent 字符串
            user_agent = request.META.get('HTTP_USER_AGENT', '')
            
            # 解析浏览器信息
            browser = self.parse_browser(user_agent)
            userLoginLog.browser = browser
            
            # 解析操作系统信息
            os_info = self.parse_os(user_agent)
            userLoginLog.os = os_info
            
            userLoginLog.login_tag = login_tag
            userLoginLog.operate_info = operate_info
            userLoginLog.status = status
            userLoginLog.login_date = datetime.datetime.now()
            userLoginLog.create_date = datetime.datetime.now()
            MySqlDb.insert_by_model(userLoginLog)
        except Exception as e:
            print(f"保存登录日志失败: {str(e)}")
    
    def parse_browser(self, user_agent):
        """从User-Agent中解析浏览器信息"""
        # 常见浏览器的正则表达式匹配
        browser_patterns = [
            (r'Edge?\/(\d+\.\d+)', 'Edge'),
            (r'MSIE (\d+\.\d+)', 'Internet Explorer'),
            (r'Chrome\/(\d+\.\d+)', 'Chrome'),
            (r'Firefox\/(\d+\.\d+)', 'Firefox'),
            (r'Safari\/(\d+\.\d+)', 'Safari'),
            (r'Opera\/(\d+\.\d+)', 'Opera')
        ]
        
        for pattern, browser_name in browser_patterns:
            match = re.search(pattern, user_agent)
            if match:
                version = match.group(1)
                return f"{browser_name} {version}"
        
        return "未知浏览器"
    
    def parse_os(self, user_agent):
        """从User-Agent中解析操作系统信息"""
        # 操作系统匹配模式
        os_patterns = [
            (r'Windows NT 10\.0', 'Windows 10'),
            (r'Windows NT 6\.3', 'Windows 8.1'),
            (r'Windows NT 6\.2', 'Windows 8'),
            (r'Windows NT 6\.1', 'Windows 7'),
            (r'Windows NT 6\.0', 'Windows Vista'),
            (r'Windows NT 5\.1', 'Windows XP'),
            (r'Windows NT 5\.0', 'Windows 2000'),
            (r'Mac OS X (\d+[_.]\d+[_.]\d+)', 'Mac OS X'),
            (r'Mac OS X (\d+[_.]\d+)', 'Mac OS X'),
            (r'Linux', 'Linux'),
            (r'Android (\d+\.\d+)', 'Android'),
            (r'iPhone OS (\d+[_.]\d+)', 'iOS')
        ]
        
        for pattern, os_name in os_patterns:
            match = re.search(pattern, user_agent)
            if match:
                if '(' in os_name:
                    version = match.group(1)
                    if '_' in version:
                        version = version.replace('_', '.')
                    return os_name.replace('(', '').replace(')', '').replace('\\1', version)
                return os_name
        
        return "未知操作系统"


'''进入用户界面'''
def to_user(request):
    return render(request, "page/system/sys_user.html")

from common.db_util import MySqlDb

'''用户列表数据，api接口'''
class UserList(APIView):
    def get(self, request):
        # 获取查询参数
        params = request.GET.dict()
        print("params:",params)
        where_clause = ""
        #用户名称
        username = params.get("username")
        if username:
            where_clause += f" and username like '%{username}%'"
        #状态信息
        status = params.get("status")
        if status:
            status = int(status)
            if status == -1:
                where_clause += " and status in (0,1)"
            else:
                where_clause += " and status = :status"
        #查询数据库，用户列表数据
        sql = "select * from sys_user where 1=1 "
        #拼接sql
        if where_clause:
            sql += where_clause
        #user_list= MySqlDb.query(sql,params)
        #获取分页参数信息
        page = params.get("page")
        page_size = params.get("page_size")
        if page is None:
            page = 1
        if page_size is None:
            page_size = 10
        #调用分页函数的接口
        result=MySqlDb.query_by_page(sql,params,page=page,page_size=page_size)
        #把数据返回到前端
        return Response(Result(data=result))

'''新增用户'''
class UserAdd(APIView):
    def post(self, request):
        # 获取请求参数
        params = request.data
        print("params:",params)
        user:User = User()
        #取出前端传来的参数：username,password,real_name,email,phone,status,is_admin,update_time,job_name,remark
        user.username = params.get("username")
        user.password = params.get("password")
        user.real_name = params.get("real_name")
        user.email = params.get("email")
        user.phone = params.get("phone")
        user.status = params.get("status")
        user.is_admin = params.get("is_admin")
        user.update_time = now()
        user.create_time = now()
        user.job_name = params.get("job_name")
        user.remark = params.get("remark")
        result = MySqlDb.insert_by_model(user)
        if result:
            return Response(Result(data=1))
        else:
            return Response(Result(code=444,msg="新增失败！",data=0))


'''用户信息修改'''
class UserModify(APIView):
    def post(self, request):
        # 获取请求参数
        params = request.data
        print("params:",params)
        user:User = User()
        #取出前端传来的参数：username,password,real_name,email,phone,status,is_admin,update_time,job_name,remark

        session = MySqlDb.get_mysql_session()
        try:
            #查询出用户信息
            user:User = session.query(User).filter(User.id==params.get("id")).first()
            if user:
                #更新用户信息
                user.username = params.get("username")
                user.password = params.get("password")
                user.real_name = params.get("real_name")
                user.email = params.get("email")
                user.phone = params.get("phone")
                user.status = params.get("status")
                user.is_admin = params.get("is_admin")
                user.update_time = now()
                user.job_name = params.get("job_name")
                user.remark = params.get("remark")
                session.commit()
                return Response(Result(data=1))
        except Exception as e:
            print(e)
            session.rollback()
            return Response(Result(code=444,msg="更新失败！==>"+e.__str__(),data=0))
        finally:
            if session:
                session.close()

'''删除用户'''
class UserDelete(APIView):
    def get(self, request):
        # 获取请求参数
        params = request.GET.dict()
        print("params:",params)
        id = params.get("id")
        #sql删除，物理删除
        sql = "delete from sys_user where id = :id"
        result = MySqlDb.delete(sql,params)
        if result:
            return Response(Result(data=1))
        else:
            return Response(Result(code=444,msg="删除失败！",data=0))

'''批量删除用户'''
class UserDeleteBatch(APIView):
    def post(self, request):
        # 获取请求参数
        params = request.data
        print("params:",params)
        ids = params.get("ids")
        ids_str = ""
        for id in ids:
            ids_str += f"{id},"
        #去掉最后一个逗号
        ids_str = ids_str[:-1]
        params = {
            "ids":ids_str
        }
        #sql删除，物理删除
        sql = "delete from sys_user where id in (:ids)"
        result = MySqlDb.delete(sql,params)
        if result:
            return Response(Result(data=1))
        else:
            return Response(Result(code=444,msg="删除失败！",data=0))


''''组装角色树'''
class UserRoleSelectTree(APIView):
    def get(self, request):
        print("=========== 进入到了RoleSelectTree ==========")
        # 请求参数
        params = request.GET.dict()
        print("请求参数：", params)
        #查询出所有的角色
        sql = "select * from sys_role where status=1"
        list = MySqlDb.query(sql, params=params)
        """组装角色列表"""
        role_tree=[]
        for item in list:
            role_tree.append({"id":item["id"],"label":item["role_name"],"expanded":True,"checked":False})
        """计算是否存在已授权情况"""
        user_id = params.get("user_id")
        temp_user_role_dict = {}
        if user_id:
            #查询出用户的角色
            sql = "select role_id from sys_user_role where user_id=:user_id"
            user_role_list = MySqlDb.query(sql, params=params)
            for item in user_role_list:
                temp_user_role_dict[item["role_id"]]=item["role_id"]

        #计算是否存在已授权情况
        for item in role_tree:
            role_id = item["id"]
            if role_id in temp_user_role_dict:
                item["checked"]=True
            else:
                item["checked"]=False

        return Response(Result(data=role_tree))

"""更新或追加用户授权角色"""
class UserRoleUpdate(APIView):
    def post(self, request):
            print("=========== 进入到了UserRoleUpdate ==========")
            # 请求参数
            params = request.data
            print("请求参数：", params)
            user_id = params.get("user_id")
            #获取角色列表
            role_ids = params.get("role_ids")


            #删除用户的角色
            sql = "delete from sys_user_role where user_id=:user_id"
            MySqlDb.delete(sql, params=params)
            #添加用户的角色
            for role_id in role_ids:
                userRole:UserRole = UserRole()
                userRole.user_id = user_id
                userRole.role_id = role_id
                userRole.create_time = datetime.datetime.now()
                MySqlDb.insert_by_model(userRole)

            return Response(Result(data=1))

'''退出登录'''
class UserLogout(APIView):
    def get(self, request):

        #销毁session用户会话信息
        if request.session:
            request.session.flush()
        # 重定向到登录页面
        return Response(Result(data=1))